<!--
 * @Author: wanglidong
 * @Date: 2021-05-24 11:16:11
 * @LastEditTime: 2022-03-25 09:27:59
 * @LastEditors: wanglidong
 * @Description:
 * @FilePath: \lowcode-front\src\views\contract\contractInitiation\contractInitiation-detail\contractInitiation-detail.vue
 * @nbsg
-->
<template>
  <div>
    <el-dialog width="70%" class="WholeScroll" :visible.sync="formShow" @close="handleClickDeal('cancel')" v-dialog-drag :modal-append-to-body="false" :close-on-click-modal="false" append-to-body>
      <span slot="title">
        <i class="iconfont icon-hetongguanli2"></i>
        <span>{{ title }}</span>
      </span>
      <div class="WholeScroll" style="max-height: 550px; overflow: auto">
        <el-form :model="formBaseData" ref="formBaseData" :rules="formBaseRules">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="基本信息" name="first">
              <el-col :span="12">
                <el-form-item label="公司" prop="companyId" :label-width="formlabelWidth">
                  <el-select style="width: 100%" v-model="formBaseData.companyId" filterable :disabled="
                      detailType === 'check' || detailType === 'approve'
                    " @change="changeDeptByCompany()">
                    <el-option v-for="(item, i) in selectList.companyList" :key="i" :label="item.fullname" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="承办部门" prop="deptId" :label-width="formlabelRightWidth">
                  <el-select style="width: 100%" v-model="formBaseData.deptId" filterable placeholder="" :disabled="
                      detailType === 'check' || detailType === 'approve'">
                    <el-option v-for="(item, i) in selectList.depts" :key="i" :label="item.fullname" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="承办人" prop="undertaker" :label-width="formlabelRightWidth">
                  <el-input style="width: 100%" v-model="formBaseData.undertaker" placeholder="" :disabled="detailType === 'check'"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="承办人电话" prop="undertakerPhone" :label-width="formlabelRightWidth">
                  <el-input style="width: 100%" v-model="formBaseData.undertakerPhone" placeholder="" :disabled="detailType === 'check'"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="合同分类" prop="newType" :label-width="formlabelWidth">
                  <el-select style="width: 100%" v-model="formBaseData.newType" filterable placeholder="" @change="changeContractType()" :disabled="
                      detailType === 'check' || detailType === 'approve'
                    ">
                    <el-option v-for="(item, i) in selectList.type" :key="i" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="合同状态" prop="contractPayStatus" :label-width="formlabelWidth">
                  <el-select style="width: 100%" v-model="formBaseData.contractPayStatus" filterable placeholder="" :disabled="
                      detailType === 'check' || detailType === 'approve'
                    ">
                    <el-option v-for="(item, i) in selectList.contractPayStatus" :key="i" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="合同名称" prop="title" :label-width="formlabelRightWidth">
                  <el-input style="width: 100%" v-model="formBaseData.title" placeholder="" :disabled="
                      detailType === 'check' || detailType === 'approve'
                    "></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="项目名称" prop="projectId" :label-width="formlabelWidth">
                  <el-select style="width: 100%" v-model="formBaseData.projectId" filterable placeholder="" @change="getBudgetApproval" :disabled="detailType === 'check'" clearable>
                    <el-option v-for="(item, i) in selectList.scopeProjects" :key="i" :label="item.proName" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同来源" prop="contractSource" :label-width="formlabelWidth">
                  <el-select style="width: 100%" v-model="formBaseData.contractSource" filterable placeholder="" :disabled="detailType === 'check'" clearable>
                    <el-option v-for="(item, i) in selectList.contractSources" :key="i" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <!-- <el-col :span="12">
                <el-form-item label="关联概算条目" prop="relatedEstimate" :label-width="formlabelWidth">
                  <el-popover placement="bottom" width="400" trigger="click">
                    <el-tree class="popover-tree" :data="budgetArr" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
                    <div slot="reference">
                      <el-input readonly v-model="formBaseData.relatedEstimateName" placeholder="选择概算条目" :disabled="detailType === 'check'"></el-input>
                    </div>
                  </el-popover>
                </el-form-item>
              </el-col> -->

              <el-col :span="12">
                <el-form-item label="合同编号" prop="number" :label-width="formlabelWidth">
                  <el-input class="contract_input" style="width: 100%" v-model="formBaseData.number" placeholder="" :disabled="
                      detailType === 'check' || detailType === 'approve'
                    "></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="合同金额" prop="amount" :label-width="formlabelWidth">
                  <el-input class="contract_input" style="width: 100%" v-model="formBaseData.amount" @blur="blurInputEvent" @keydown.native="$publicJs.changeInputLimit" type="number" placeholder="" :disabled="
                      detailType === 'check' || detailType === 'approve'
                    ">
                    <template slot="append">万元</template>
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="其中：暂列金" prop="provisionalSum" :label-width="formlabelWidth">
                  <el-input class="contract_input" style="width: 100%" v-model="formBaseData.provisionalSum" @blur="blurInputEvent_provisionalSum" type="number" @keydown.native="$publicJs.changeInputLimit" placeholder="" :disabled="
                      detailType === 'check' || detailType === 'approve'
                    ">
                    <template slot="append">万元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="变更金额" prop="changeAmount" :label-width="formlabelWidth">
                  <el-input class="contract_input" style="width: 100%" v-model="formBaseData.changeAmount" @blur="blurInputEvent" type="number" @keydown.native="$publicJs.changeInputLimit" placeholder="" :disabled="
                      detailType === 'check' || detailType === 'approve'
                    ">
                    <template slot="append">万元</template>
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="变更后合同金额" prop="afterChangeAmount" :label-width="formlabelWidth">
                  <el-input class="contract_input" style="width: 100%" v-model="formBaseData.afterChangeAmount" @blur="blurInputEvent" type="number" @keydown.native="$publicJs.changeInputLimit" placeholder="" :disabled="
                      detailType === 'check' || detailType === 'approve'
                    ">
                    <template slot="append">万元</template>
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col :span="24" style="position: relative" v-for="(item , index) in  formBaseData.contractContentGroup" :key="index">
                <div>
                  <div style="display: flex;flex-direction: row;align-items: center">
                    <el-col :span="23">
                      <el-form-item label="合同相对方(乙方)" :prop="'contractContentGroup.'+ index +'.secondPartyNoRelationName'" :label-width="formlabelRightWidth" :rules="formBaseRules.secondPartyNoRelationName">
                        <el-select style="width: 100%" v-model="item.secondParty" filterable @change="setSecondParty(item)" placeholder="" :disabled="detailType === 'check'" clearable allow-create>
                          <el-option v-for="(item, i) in selectList.supplierList" :key="i" :label="item.label" :value="item.value">
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <i class="iconfont icon-add addReduceClass" @click="changeCol('add')" v-if="index==0&&detailType != 'check'&&detailType != 'approve'"></i>
                    <i class="iconfont icon-subtract addReduceClass" v-if="index>0&&detailType != 'check'&&detailType != 'approve'" @click="changeCol('reduce',index)"></i>
                  </div>

                  <el-col :span="12">
                    <el-form-item label="合同负责人(乙方)姓名" :prop="'contractContentGroup.'+ index +'.principalOfSecondParty'" :label-width="formlabelRightWidth">
                      <el-input style="width: 100%" v-model="item.principalOfSecondParty" placeholder="" :disabled=" detailType === 'check' || detailType === 'approve' "></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="合同负责人(乙方)联系方式" :label-width="formlabelRightWidth2" :prop="'contractContentGroup.'+ index +'.principalOfSecondPartyMobile'">
                      <el-input style="width: 100%" v-model="item.principalOfSecondPartyMobile" placeholder="" :disabled="detailType === 'check' || detailType === 'approve' "></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="收款账户" :prop="'contractContentGroup.'+ index +'.payedCompanyName'" :label-width="formlabelRightWidth">
                      <el-input style="width: 100%" v-model="item.payedCompanyName" placeholder="" :disabled=" detailType === 'check' || detailType === 'approve'"></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="开户银行" :prop="'contractContentGroup.'+ index +'.depositBank'" :label-width="formlabelRightWidth2">
                      <el-input style="width: 100%" v-model="item.depositBank" placeholder="" :disabled="
                      detailType === 'check' || detailType === 'approve'
                    "></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="账号" :prop="'contractContentGroup.'+ index +'.bankAccount'" :label-width="formlabelRightWidth">
                      <el-input style="width: 100%" v-model="item.bankAccount" placeholder="" :disabled="detailType === 'check' || detailType === 'approve'"></el-input>
                    </el-form-item>
                  </el-col>

                </div>
              </el-col>

              <el-col :span="24">
                <el-form-item prop="reason" label="合同立项理由" :label-width="formlabelWidth">
                  <el-input class="fill" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="" v-model="formBaseData.reason" :disabled="detailType === 'check' || detailType === 'approve'">
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="签订时间" prop="orderDate" :label-width="formlabelWidth">
                  <el-date-picker style="width: 100%" v-model="formBaseData.orderDate" type="date" value-format="yyyy-MM-dd" placeholder="选择签订时间" :disabled="
                      detailType === 'check' || detailType === 'approve'
                    ">
                  </el-date-picker>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <div class="formTitle">附件</div>
                <cmsFileTable ref="cmsFileTable" :buildUnitTable="buildUnitTable" :fileSystem="fileSystem" :detailId="detailId" :detailType="detailType" :buttonDelShow="buttonDelShow" :showNone="showNone" :buttonCheckShow="buttonCheckShow" :buttonUploadShow="buttonUploadShow" @change="tableChange">
                </cmsFileTable>
              </el-col>
            </el-tab-pane>

          </el-tabs>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">

        <template v-if="detailType === 'build' || detailType === 'edit'">
          <el-button size="small" type="primary" :loading="isLoading" @click="handleClickDeal('submit', { flag: 1 })"><i class="iconfont icon-icon_save"></i> 确 定
          </el-button>
        </template>
        <el-button size="small" @click="handleClickDeal('cancel')"><i class="iconfont icon-icon_cancel"></i> 取 消
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import msgUtil from '@/utils/msgUtil'
import contract from '@/api/buss/contract'
import common from '@/api/buss/common';
import crudDict from '@/api/system/dict'
import { getCompanyByUserWithId } from "../../../../api/buss/contract";
import contractorManagement from '@/api/buss/contractorManagement'
import budgetApproval from '@/api/buss/budgetApproval'
export default {
  name: 'contractInitiation-detail',
  components: {

  },
  props: {
    postDetail: {
      type: Object,
      default: {
        show: false,
        type: 'build',
        params: {},
      },
    },
  },
  watch: {
    postDetail(value) {
      console.log(value)
      // 显示详情弹窗
      this.formShow = value.show
      // 初始化窗口参数
      this.activeName = 'first'
      // 详情类型
      this.detailType = value.type;
      this.buildUnitTable = [
        {
          stuffName: '合同文本',
          part: 'partOne',
          file: [{ realName: '' }],
          isNeed: false,
          loading: false,
          isMulti: true,
        },
        {
          stuffName: '其他资料',
          part: 'partTwo',
          file: [{ realName: '' }],
          isNeed: false,
          loading: false,
          isMulti: true,
        },
      ];

      this.detailId = value.detailId ? value.detailId : '';
      this.getSupplier()
      // 非新建详情时 获取详情
      if (this.detailType !== 'build') {
        // 获取详情请求
        this.getDetail()
        if (this.detailType == 'check') {
          this.title = '查看合同'
        }
        if (this.detailType == 'edit') {
          this.title = '修改合同'
        }
      }
      if (this.detailType === 'build') {
        this.title = '合同登记'
      }
      this.initData()
    },
  },
  data() {
    return {
      projectMustSelect: false,
      newDetName: '',
      isLoading: false,
      detailType: 'build', // 详情类型 build新建 check不可编辑查看 edit编辑
      detailId: '', // 当前详情的id
      detailActions: [], // 当前详情的操作项
      formShow: false, // 表单展示
      formlabelWidth: '150px', // 表单左侧标题宽度
      formlabelRightWidth: '150px', // 表单左侧标题宽度
      formlabelRightWidth2: '180px', // 表单左侧标题宽度
      formlabelWidth2: '120px', // 表单左侧标题宽度
      title: '合同审批立项',
      activeName: 'first',
      // 所有下拉框列表的集合
      selectList: {
        //公司列表
        companyList: [],
        //  公司列表根据类型过滤后的结果
        companyListFiltered: [],
        //  可以选择的项目列表
        scopeProjects: [],
        //部门
        depts: [],
        file: [], // 文件
        //  标段负责人选择项
        secondPartUserOpts: [],
        contractSources: [],
        contractPayStatus: [
          { value: 1, label: '执行中' }, { value: 2, label: '办结' }
        ],
        supplierList: [],
      },
      budgetArr: [],
      // 表单基本信息内容
      formBaseData: {
        contractPayStatus: '',
        memberUids: [],
        contractContentGroup: [{
          bankAccount: '',
          depositBank: '',
          payedCompanyName: '',
          principalOfSecondPartyMobile: '',
          principalOfSecondParty: '',
          secondPartyNoRelationName: '',
        }],
        //合同信息
        number: '',
        title: '',
        amount: '',
        newType: '',
        secondParty: '',
        length: '',
        secondPartyNoRelationName: '',
        principalOfSecondParty: '',
        principalOfSecondPartyMobile: '',
        payedCompanyName: '',
        depositBank: '',
        bankAccount: '',
        constructionCompany: '',
        associatedBlock: '',
        orderDate: '',
        companyId: '',
        deptId: '',
        projectId: '',
        undertaker: '',
        contractSource: '',
        provisionalSum: '',
        reason: '',
        undertakerPhone: '',
        relatedEstimateName: '',
        relatedEstimate: '',
      },
      // 表单基本信息验证
      formBaseRules: {
        companyId: [{
          required: true, message: '请输入' + '公司', trigger: 'blur'
        }],
        title: [
          { required: true, message: '请输入' + '合同名称', trigger: 'blur' },
        ],
        number: [
          { required: true, message: '请输入' + '合同编号', trigger: 'blur' },
        ],
        amount: [
          { required: true, message: '请输入' + '合同总金额', trigger: 'blur' },
        ],
        newType: [
          { required: true, message: '请选择' + '合同分类', trigger: 'change' },
        ],
        projectId: [
          { required: true, message: '请选择' + '所属项目', trigger: 'change' },
        ],
        contractPayStatus: [
          { required: true, message: '请选择' + '合同状态', trigger: 'blur' },
        ],
        typeCode: [
          {
            required: true,
            message: '请输入' + '合同分类编号',
            trigger: 'change',
          },
        ],

        contractSource: [
          { required: true, message: '请选择' + '合同来源', trigger: 'change' },
        ],

        sectionIds: [
          {
            required: true,
            message: '请选择' + '标段',
            trigger: 'change',
          },
        ],
        secondPartyNoRelationName: [
          {
            required: true,
            message: '请输入' + '合同签订单位(乙方)',
            trigger: 'blur',
          },
        ],
        basisOfDecision: [
          {
            required: true,
            message: '请输入' + '合同立项理由',
            trigger: 'blur',
          },
        ],

        associatedBlock: [
          { required: true, message: '请选择' + '关联标段', trigger: 'change' },
        ],
        scopeProjects: [
          { required: true, message: '请选择' + '所属项目', trigger: 'change' },
        ],
        depts: [
          {
            required: true,
            message: '请选择' + '所属经办部门',
            trigger: 'change',
          },
        ],

        memberUids: [
          {
            required: true,
            message: '请选择' + '乙方单位参与人',
            trigger: 'change',
          },
        ],
        //
        // deptId: [
        //   { required: true, message: '请选择' + '经办部门', trigger: 'change' },
        // ],

      },
      //  允许标段选择项
      enableSectionSelection: false,
      defaultProps: {
        children: 'children',
        label: 'projectCostName',
      },
      //  是否需要选择是否总承包
      enableWhetherManageSelection: false,
      //  是否需要出现标段
      // enableSection: false,
      //  是否需要显示部门名称
      buildUnitTable: [
        {
          stuffName: '合同文本',
          part: 'partOne',
          file: [{ realName: '' }],
          isNeed: false,
          loading: false,
          isMulti: true,
        },
        {
          stuffName: '其他资料',
          part: 'partTwo',
          file: [{ realName: '' }],
          isNeed: false,
          loading: false,
          isMulti: true,
        },
      ],
      fileSystem: {
        attachId: {
          partOne: '',
          partTwo: '',
          partThree: '',
          partFour: '',
          other: '',
          taohong: '',
        },
        sys: 'buss',
        module: 'contractManage',
        entityClass: 'contractManage',
        viewByAnon: true,
        longLife: false,
        part: {
          partOne: 'partOne',
          partTwo: 'partTwo',
          partThree: 'partThree',
          partFour: 'partFour',
          other: 'other',
        },
      },
      //  显示审核提交按钮
      showAuditBtn: false,
      saveUnZeroData: [],
      isAudit: '',
    }
  },

  filters: {
    moneyFilter(value) {
      try {
        let before = value.toFixed(2)
        before = before.toString()
        let num = before.split('.')[0]
        let numSmall = before.split('.')[1]
        let result = [],
          counter = 0
        num = (num || 0).toString().split('')
        for (let i = num.length - 1; i >= 0; i--) {
          counter++
          result.unshift(num[i])
          if (!(counter % 3) && i != 0) {
            result.unshift(',')
          }
        }
        let after =
          numSmall === undefined
            ? result.join('')
            : result.join('') + '.' + numSmall
        return after
      } catch (e) {
        return ''
      }
    },
  },
  created() {
  },
  methods: {
    handleNodeClick(data) {
      this.$set(this.formBaseData, 'relatedEstimate', data.id)
      let relatedEstimateName = ''
      if (data.fathers != null && data.fathers.length > 0) {
        data.fathers.forEach(item => {
          relatedEstimateName = relatedEstimateName + item.projectCostName + '/'
        })
        relatedEstimateName = relatedEstimateName + data.projectCostName
        this.$set(this.formBaseData, 'relatedEstimateName', relatedEstimateName)
      } else {
        this.$set(this.formBaseData, 'relatedEstimateName', data.projectCostName)
      }
    },
    getBudgetApproval() {
      budgetApproval.getBudgetApprovalTree(this.formBaseData.projectId).then(res => {
        if (res.code == 200) {
          this.budgetArr = res.data
          if (this.budgetArr) {
            this.budgetArr.forEach(node => {
              this.convertAsDoubleTree(node, []);
            });
          }
        } else {
          msgUtil.error2(res.data.message)
        }
      })
    },
    /**
     * 将后端返回的树结构数据转为双向树结构
     * 子节点存放其父节点全部对象。
     * 可以向上遍历
     * 在子节点被修改数据时
     * 用于清空父级数据
     * 递归深度遍历，如果性能太差再考虑消递归
     */
    convertAsDoubleTree(tree, fathers) {
      if (fathers == null) {
        fathers = [];
      }
      tree.fathers = [];
      fathers.forEach(f => {
        tree.fathers.push(f);
      })
      //  往下设置
      if (!tree.treeLeaf) {
        if (tree.children) {
          tree.children.forEach(child => {
            let newFather = [];
            fathers.forEach(f => {
              newFather.push(f);
            })
            newFather.push(tree);
            this.convertAsDoubleTree(child, newFather);
          });
        }
      }
    },
    setSecondParty(val) {
      let find = false
      this.selectList.supplierList.forEach(item => {
        if (item.value == val.secondParty) {
          find = true
          val.secondPartyNoRelationName = item.label
        }
      })
      if (!find) { val.secondPartyNoRelationName = val.secondParty }
    },
    getSupplier() {
      contractorManagement.getSupplier().then(res => {
        if (res.code === 200) {
          let list = res.data.map(e => {
            return { value: e.id, label: e.enterpriseName }
          })
          this.selectList.supplierList = list
          // for (var i in data) {
          //   this.selectList.supplierList.push({ 'value': data[i].id, 'label': data[i].enterpriseName });
          // }
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取问题归属失败")
      })
    },
    changeCol(val, index) {
      /* console.log(event)*/
      if (val == 'add') {
        this.formBaseData.contractContentGroup.push({
          bankAccount: '',
          depositBank: '',
          payedCompanyName: '',
          principalOfSecondPartyMobile: '',
          principalOfSecondParty: '',
          secondPartyNoRelationName: '',
        })
      } else if (val == 'reduce') {
        this.formBaseData.contractContentGroup.splice(index, 1)
      }
      this.$forceUpdate()
    },
    initData() {
      this.selectList.type = []
      this.selectList.contractSources = []
      this.selectList.companyList = []

      crudDict.getByCode('contractType').then(res => {
        if (res.code === 200) {
          var data = res.data;
          for (var i in data) {
            this.selectList.type.push({ 'value': data[i].id, 'label': data[i].name });
          }
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取问题归属失败")
      })

      crudDict.getByCode('contractSource').then(res => {
        if (res.code === 200) {
          var data = res.data;
          for (var i in data) {
            this.selectList.contractSources.push({ 'value': data[i].id, 'label': data[i].name });
          }
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取问题归属失败")
      })

      if (this.detailType === 'build') {
        contract.getCompanyByUser().then(res => {
          if (res.status === 1) {
            this.selectList.companyList = res.data
            return new Promise(reslove => {
              reslove(res)
            })
          } else {
            msgUtil.error2(res.data.message)
          }
        }).catch(res => {
          console.log('请求出现错误', res);
          msgUtil.error2('获取部门用户列表失败!')
        })
      }
    },

    getCompanyByUserWithId(val) {
      this.selectList.companyList = []
      return contract.getCompanyByUserWithId(val).then(res => {
        if (res.status === 1) {
          this.selectList.companyList = res.data
          return new Promise(reslove => {
            reslove(res)
          })
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(res => {
        console.log('请求出现错误', res);
        msgUtil.error2('获取部门用户列表失败!')
      })
    },


    changeDeptByCompany() {
      this.formBaseData.projectId = ''
      this.selectList.scopeProjects = []
      this.formBaseData.deptId = ''
      this.selectList.depts = []
      this.getDeptByCompany().then(res => {
        this.getProjectsByCompanyId()
      })
    },

    getDeptByCompany() {
      return contract.getDeptByCompany(this.formBaseData.companyId).then(res => {
        if (res.status === 1) {
          this.selectList.depts = res.data
          return new Promise(reslove => {
            reslove(res)
          })
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(res => {
        console.log('请求出现错误', res);
        msgUtil.error2('获取部门用户列表失败!')
      })
    },
    getProjectsByCompanyId() {
      return common.getScopeProjects(this.formBaseData.companyId).then(res => {
        if (res.code === 200) {
          this.selectList.scopeProjects = res.data
          return new Promise(reslove => {
            reslove(res)
          })
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(res => {
        console.log('请求出现错误', res);
        msgUtil.error2('获取部门用户列表失败!')
      })
    },
    blurInputEvent() {
      if (this.formBaseData.amount) {
        this.formBaseData.amount = Number(this.formBaseData.amount)
      }
      if (this.formBaseData.changeAmount) {
        this.formBaseData.changeAmount = Number(this.formBaseData.changeAmount)
      }

      if (this.formBaseData.afterChangeAmount) {
        this.formBaseData.afterChangeAmount = Number(this.formBaseData.afterChangeAmount)
      }
    },
    blurInputEvent_provisionalSum() {
      if (this.formBaseData.provisionalSum) {
        this.formBaseData.provisionalSum = Number(this.formBaseData.provisionalSum)
      }
    },

    changeContractType() {
      this.formBaseData.title = ''
      this.formBaseData.projectId = ''
      this.formBaseData.contractSource = ''
      this.formBaseData.contractPayStatus = ''
      this.formBaseData.number = ''
      this.formBaseData.amount = ''
      this.formBaseData.provisionalSum = ''
      this.formBaseData.secondPartyNoRelationName = ''
      this.formBaseData.principalOfSecondParty = ''
      this.formBaseData.principalOfSecondPartyMobile = ''
      this.formBaseData.payedCompanyName = ''
      this.formBaseData.depositBank = ''
      this.formBaseData.bankAccount = ''
      this.formBaseData.reason = ''
      this.formBaseData.orderDate = ''


      this.selectList.type.forEach(item => {
        if (this.formBaseData.newType == item.value
          && (item.label == '检测类' || item.label == '勘察设计类' || item.label == '咨询类' || item.label == '征拆类')) {
          this.projectMustSelect = true
        }
      })
    },


    // 获取详情请求 api
    getDetail() {
      contract.getOne(this.detailId).then(res => {
        if (res.status == 1) {
          this.formBaseData = res.data
          this.$set(this.formBaseData, 'reason', '')
          this.getDeptByCompany()
          this.getProjectsByCompanyId()
          this.formBaseData.id = res.data.id
          this.formBaseData.reason = res.data.basisOfDecision
          this.formBaseData.newType = res.data.contractType
          this.formBaseData.projectId = res.data.projectId
          this.getBudgetApproval()
          this.formBaseData.deptId = res.data.deptId
          this.getCompanyByUserWithId(res.data.applyUser)
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取详情信息失败")
      })

    },


    // 提交详情 提交1/暂存0 新建0/修改1
    submitDetail(type, callback) {
      if (this.projectMustSelect) {
        if (!this.formBaseData.projectId || (this.formBaseData.projectId == '')) {
          this.isLoading = false
          msgUtil.error2("该合同类型下项目必选")
          return
        }
      }

      //  '/japi/contractapply/resubmit'
      if (this.detailType === 'build') {
        contract.submit(this.formBaseData).then(res => {
          if (res.status === 1) {
            this.detailId = res.data.id
            //this.isLoading = false
            this.$notify({
              title: '数据新增成功',
              type: 'success',
              duration: 1500
            })
            this.saveFiles()
            // 传值给父组件刷新列表
            this.$emit('reloadList')
            this.formShow = false

          } else {
            msgUtil.error2(res.data.message)
          }
        }).catch((response) => {
          this.$notify({
            title: '数据新增失败',
            type: 'error',
            duration: 2500
          })
        }).finally((response) => {
          this.isLoading = false
        })
      } else {
        contract.resubmit(this.formBaseData).then(res => {
          if (res.status === 1) {
            this.detailId = res.data.id
            //this.isLoading = false
            this.$notify({
              title: '数据修改成功',
              type: 'success',
              duration: 1500
            })
            this.saveFiles()
            // 传值给父组件刷新列表
            this.$emit('reloadList')
            this.formShow = false

          } else {
            msgUtil.error2(res.data.message)
          }
        }).catch((response) => {
          this.$notify({
            title: '数据表新增失败',
            type: 'error',
            duration: 2500
          })
        }).finally((response) => {
          this.isLoading = false
        })
      }
    },

    // 点击各个流程的按钮事件
    handleClickDeal(type, res) {
      console.log(type, res)
      switch (type) {
        // 取消，关闭窗口
        case 'cancel':
          // 重置表单验证
          this.$refs['formBaseData'].resetFields()
          // 清空表单内容
          this.formBaseData = {
            contractPayStatus: '',
            memberUids: [],
            //合同信息
            number: '',
            title: '',
            amount: '',
            newType: '',
            secondParty: '',
            length: '',
            secondPartyNoRelationName: '',
            principalOfSecondParty: '',
            principalOfSecondPartyMobile: '',
            payedCompanyName: '',
            depositBank: '',
            bankAccount: '',
            constructionCompany: '',
            associatedBlock: '',
            contractContentGroup: [{
              bankAccount: '',
              depositBank: '',
              payedCompanyName: '',
              principalOfSecondPartyMobile: '',
              principalOfSecondParty: '',
              secondPartyNoRelationName: '',
            }],
            orderDate: '',
            companyId: '',
            deptId: '',
            projectId: '',
            undertaker: '',
            contractSource: '',
            provisionalSum: '',
            reason: '',
            undertakerPhone: '',
            relatedEstimateName: '',
            relatedEstimate: '',
          } // 表单基本信息内容
          // 清空文件
          this.selectList.file = []
          // 关闭弹窗
          this.formShow = false
          this.enableSectionSelection = false
          this.showAuditBtn = false
          this.detailId = ''
          break
        // 保存
        case 'submit':
          let flag = res.flag
          // 表单验证
          this.$refs['formBaseData'].validate((valid) => {
            if (valid) {
              // 再验证其他内容
              // 整理文件信息
              this.isLoading = true
              // 提交详情
              this.submitDetail(flag, () => {
                this.saveFiles()
              })
            } else {
              this.isLoading = false
            }
          })
          break
        // 删除

      }
    },

    saveFiles() {
      this.$refs['cmsFileTable'].bindAllFile(this.detailId)
    },



    /**
     *显示删除按钮
     * @param row
     */
    buttonDelShow(row) {
      let flag = false
      if (
        (this.detailType === 'build' || this.detailType === 'edit') &&
        row.file[0].realName !== '' &&
        !row.isNeed
      ) {
        flag = true
      }
      // 经办人操作时
      // if ((this.detailType!=='build'&&this.detailType!=='edit'&&this.detailType!=='check')&&this.isReport&&row.file[0].realName!==''&&!row.isNeed) {
      //   flag=true
      // }
      // 多文件上传的控制的控制
      if (row.isMulti) {
        flag = false
      }
      return flag
    },


    /**
     *控制显示暂无文件
     * @param row
     */
    showNone(row) {
      let flag = false
      if (
        this.detailType !== 'build' &&
        this.detailType !== 'edit' &&
        row.file[0].realName === ''
      ) {
        flag = true
      }
      // 经办人操作时
      // if ((this.detailType!=='build'&&this.detailType!=='edit'&&this.detailType!=='check')&&this.isReport) {
      //   flag=false
      // }
      return flag
    },
    /**
     * 控制查看按钮显示
     * @param row
     */
    buttonCheckShow(row) {
      let flag = false
      if (
        this.detailType !== 'build' &&
        this.detailType !== 'edit' &&
        row.file[0].realName !== ''
      ) {
        flag = true
      }
      // 经办人操作时
      // if ((this.detailType!=='build'&&this.detailType!=='edit'&&this.detailType!=='check')&&this.isReport) {
      //   flag=false
      // }
      // 多文件上传的控制的控制
      if (row.isMulti) {
        flag = false
      }
      return flag
    },
    /**
     * 控制上传按钮显示
     * @param row
     * @returns {boolean}
     */
    buttonUploadShow(row) {
      let flag = false
      if (
        this.detailType === 'build' ||
        this.detailType === 'edit' ||
        this.detailType === 'approve'
      ) {
        flag = true
      }
      // 经办人操作时
      // if ((this.detailType!=='build'&&this.detailType!=='edit'&&this.detailType!=='check')&&this.isReport) {
      //   flag=true
      // }
      return flag
    },
    tableChange(val) {
      this.$set(this, 'buildUnitTable', [...val])
    },


    handleClick() {
    },

    moneyFilter(value) {
      try {
        let before = value.toFixed(2)
        before = before.toString()
        let num = before.split('.')[0]
        let numSmall = before.split('.')[1]
        let result = [],
          counter = 0
        num = (num || 0).toString().split('')
        for (let i = num.length - 1; i >= 0; i--) {
          counter++
          result.unshift(num[i])
          if (!(counter % 3) && i != 0) {
            result.unshift(',')
          }
        }
        let after =
          numSmall === undefined
            ? result.join('')
            : result.join('') + '.' + numSmall
        return after
      } catch (e) {
        return ''
      }
    },
  },
}
</script>

<style scoped lang="scss">
.el-select.half {
  width: 250px;
}

.el-select.fill {
  width: 800px;
}

.contract_input {
  width: 250px;
}

.contract_input2 {
  width: 240px;
}

.el-input .el-select {
  width: 130px;
}

.fee_add {
  color: #008fe0;
  border-color: #008fe0;
  float: right;
  margin-bottom: 10px;
}
.addReduceClass {
  position: absolute;
  right: 10px;
  font-size: 40px;
  top: -5px;
  cursor: pointer;
}
.addReduceClass:hover {
  color: #66b1ff;
}
</style>
